package fr.ul.ade.prime.analyzer;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import fr.ul.ade.prime.config.Config;

public class XmlFetcher extends BufferedInputStream {

	private static final int BUFFER_SIZE = 1024;

	private StringBuilder rawXml;

	public XmlFetcher(InputStream in) {
		super(in, BUFFER_SIZE);
		this.rawXml = new StringBuilder();
	}// XmlFetcher(InputStream)

	@Override
	public synchronized int read() throws IOException {
		int read = super.read();
		this.rawXml.append((char) read);
		return read;
	}// read()

	@Override
	public synchronized int read(byte[] buffer, int offset, int byteCount)
			throws IOException {
		int nRead = super.read(buffer, offset, byteCount);
		if (nRead != -1)
			this.rawXml.append(new String(buffer, offset, nRead));
		return nRead;
	}// read(byte[], int, int)

	@Override
	public void close() {
		try {
			super.close();
		} catch (IOException ioe) {
			/* On ne fait rien, le flot sera fermé tôt où tard. */
		}// try
	}// close()

	public String getRawXml() {
		return this.rawXml.toString();
	}// getRawXml()

	public static XmlFetcher buildXmlFetcher(String url) throws Exception {
		URL u = new URL(url);
		URLConnection conn = u.openConnection();
		conn.setReadTimeout(Config.READ_TIMEOUT);
		conn.setConnectTimeout(Config.CONNECTION_TIMEOUT);
		conn.connect();
		return new XmlFetcher(conn.getInputStream());
	}// buildXmlFetcher(String)

}// class XmlFetcher